Installation & Setup
Install SQLite
bash
1# Ubuntu / Debian2sudo apt update3sudo apt install -y sqlite34
5# Fedora / RHEL6sudo dnf install -y sqlite7
8# macOS (pre-installed or Homebrew)9brew install sqlite10
11# Verify12sqlite3 --versionConnect to SQLite
bash
1# Open/create database2sqlite3 mydb.db3
4# Open in-memory database5sqlite3 :memory:6
7# Open with specific options8sqlite3 -header -csv mydb.db # CSV output with headers9sqlite3 -column -header mydb.db # Column output with headers10sqlite3 -json mydb.db # JSON output (SQLite 3.33+)11sqlite3 -line mydb.db # Line output12
13# Execute query and exit14sqlite3 mydb.db "SELECT * FROM users;"15
16# Execute multiple queries17sqlite3 mydb.db "SELECT COUNT(*) FROM users; SELECT * FROM users LIMIT 5;"18
19# Execute SQL file20sqlite3 mydb.db < script.sql21
22# Show help23sqlite3 --helpSQLite Shell Commands
Database Operations
bash
1.open mydb.db # Open database2.quit # Exit3.exit # Same as .quit4.headers on # Enable column headers5.headers off # Disable column headers6.mode column # Column-aligned output7.mode csv # CSV output8.mode tsv # Tab-separated output9.mode line # One line per row10.mode list # Separator-delimited (default)11.mode json # JSON output (SQLite 3.33+)12.mode markdown # Markdown table13.mode table # Box-drawing table14.mode insert # SQL INSERT statements15.mode quote # Quoted values16.separator "," # Set CSV separator17.width 10 20 30 # Set column widths18
19.output results.txt # Redirect output to file20.output stdout # Redirect output to stdout21.once filename.txt # Write next query to file22
23.read script.sql # Execute SQL file24.import data.csv tablename # Import CSV25.import --csv data.csv tablename # Explicit CSV import (SQLite 3.32+)26.import --skip 1 data.csv tablename # Skip header row27
28.databases # List databases29.tables # List tables30.table tablename # Check if table exists31.schema tablename # Show CREATE TABLE statement32.schema # Show all table schemas33
34.indexes tablename # List indexes for table35.indexes # List all indexes36
37.stats # Show statistics38.bail on # Stop on errors39.bail off # Continue on errors40.explain on # Explain mode (show opcodes)41.explain off42
43.timer on # Show query execution time44.timer offUseful Meta-Commands
bash
1.fullschema # Show complete schema (tables, views, triggers, indexes)2.indices # Same as .indexes3.pragma # Show all pragma values4
5# Get table info6PRAGMA table_info(users); # Column names, types, constraints7PRAGMA table_xinfo(users); # Extended info (including hidden columns)8
9# Get foreign key info10PRAGMA foreign_key_list(users);11
12# Database file info13PRAGMA database_list; # List attached databases14PRAGMA journal_mode; # Current journal mode15PRAGMA page_count; # Number of pages16PRAGMA page_size; # Page size in bytes17PRAGMA freelist_count; # Free pages18PRAGMA integrity_check; # Check database integritySQL Reference
Create Tables
sql
1-- Basic table2CREATE TABLE users (3 id INTEGER PRIMARY KEY AUTOINCREMENT,4 username TEXT NOT NULL UNIQUE,5 email TEXT NOT NULL,6 age INTEGER,7 is_active BOOLEAN DEFAULT 1,8 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,9 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP10);11
12-- Table with constraints13CREATE TABLE orders (14 id INTEGER PRIMARY KEY AUTOINCREMENT,15 user_id INTEGER NOT NULL,16 total DECIMAL(10,2) NOT NULL,17 status TEXT DEFAULT 'pending',18 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,19 FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE20);21
22-- Table with CHECK constraint23CREATE TABLE products (24 id INTEGER PRIMARY KEY AUTOINCREMENT,25 name TEXT NOT NULL,26 price DECIMAL(10,2) CHECK (price >= 0),27 quantity INTEGER CHECK (quantity >= 0)28);29
30-- Temporary table31CREATE TEMPORARY TABLE tmp_results AS SELECT * FROM users WHERE is_active = 1;32
33-- Create table with specific collation34CREATE TABLE names (35 name TEXT COLLATE NOCASE -- Case-insensitive comparison36);Alter Tables
sql
1-- Add column (SQLite 3.35+)2ALTER TABLE users ADD COLUMN phone TEXT;3
4-- Drop column (SQLite 3.35+)5ALTER TABLE users DROP COLUMN phone;6
7-- Rename table8ALTER TABLE users RENAME TO members;9
10-- Rename column (SQLite 3.25+)11ALTER TABLE users RENAME COLUMN username TO login_name;Insert Data
sql
1-- Single row2INSERT INTO users (username, email, age) VALUES ('alice', 'alice@example.com', 30);3
4-- Multiple rows5INSERT INTO users (username, email, age) VALUES6 ('bob', 'bob@example.com', 25),7 ('charlie', 'charlie@example.com', 35);8
9-- Insert from SELECT10INSERT INTO users_backup (username, email, age)11 SELECT username, email, age FROM users WHERE is_active = 1;12
13-- Insert or replace (upsert)14INSERT OR REPLACE INTO users (username, email, age)15 VALUES ('alice', 'alice@new.com', 31);16
17-- Insert or ignore (skip duplicates)18INSERT OR IGNORE INTO users (username, email, age)19 VALUES ('alice', 'alice@example.com', 30);20
21-- Insert on conflict (SQLite 3.24+)22INSERT INTO users (username, email, age)23 VALUES ('alice', 'alice@example.com', 30)24 ON CONFLICT(username) DO UPDATE SET email = excluded.email, age = excluded.age;Query Data
sql
1-- Basic select2SELECT * FROM users;3SELECT id, username, email FROM users;4
5-- Where clause6SELECT * FROM users WHERE age > 25;7SELECT * FROM users WHERE age BETWEEN 25 AND 35;8SELECT * FROM users WHERE username LIKE 'alice%';9SELECT * FROM users WHERE username IN ('alice', 'bob');10SELECT * FROM users WHERE email IS NOT NULL;11
12-- Order by13SELECT * FROM users ORDER BY created_at DESC;14SELECT * FROM users ORDER BY age ASC, username DESC;15
16-- Limit and offset17SELECT * FROM users LIMIT 10;18SELECT * FROM users LIMIT 10 OFFSET 20; -- Skip first 2019SELECT * FROM users LIMIT 10, 20; -- Alternative syntax20
21-- Aggregate functions22SELECT COUNT(*) FROM users;23SELECT AVG(age) FROM users;24SELECT MIN(age), MAX(age) FROM users;25SELECT SUM(total) FROM orders WHERE status = 'completed';26
27-- Group by28SELECT status, COUNT(*) AS count, AVG(total) AS avg_total29FROM orders30GROUP BY status;31
32-- Having33SELECT status, COUNT(*) AS count34FROM orders35GROUP BY status36HAVING COUNT(*) > 5;37
38-- JOINs39SELECT u.username, o.total, o.status40FROM users u41INNER JOIN orders o ON u.id = o.user_id;42
43SELECT u.username, COALESCE(SUM(o.total), 0) AS total_spent44FROM users u45LEFT JOIN orders o ON u.id = o.user_id46GROUP BY u.username;47
48-- Subqueries49SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100);50
51-- EXISTS52SELECT * FROM users u WHERE EXISTS (53 SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.total > 10054);55
56-- UNION57SELECT username FROM users WHERE is_active = 158UNION59SELECT username FROM users WHERE age > 30;60
61-- Common Table Expression (CTE)62WITH active_users AS (63 SELECT * FROM users WHERE is_active = 164)65SELECT * FROM active_users WHERE age > 25;66
67-- Window functions (SQLite 3.25+)68SELECT username, age,69 RANK() OVER (ORDER BY age DESC) AS age_rank,70 ROW_NUMBER() OVER (ORDER BY created_at) AS row_num,71 SUM(total) OVER (PARTITION BY user_id) AS user_total72FROM users;73
74-- CASE expression75SELECT username,76 CASE77 WHEN age < 25 THEN 'Young'78 WHEN age BETWEEN 25 AND 40 THEN 'Adult'79 ELSE 'Senior'80 END AS age_group81FROM users;Update Data
sql
1UPDATE users SET age = 31 WHERE username = 'alice';2UPDATE users SET is_active = 0 WHERE age < 18;3UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = 5;4
5-- Update with JOIN-like behavior6UPDATE orders SET status = 'expired'7WHERE created_at < date('now', '-30 days') AND status = 'pending';8
9-- Update or insert10INSERT INTO settings (key, value) VALUES ('theme', 'dark')11ON CONFLICT(key) DO UPDATE SET value = excluded.value;Delete Data
sql
1DELETE FROM users WHERE id = 5;2DELETE FROM users WHERE is_active = 0;3DELETE FROM orders WHERE created_at < date('now', '-365 days');4
5-- Delete all rows (fast)6DELETE FROM users;7
8-- Delete with limit (requires specific approach)9DELETE FROM users WHERE rowid IN (10 SELECT rowid FROM users WHERE is_active = 0 LIMIT 100011);PRAGMA (Database Configuration)
Performance PRAGMAs
sql
1-- Journal mode (affects durability vs performance)2PRAGMA journal_mode = WAL; -- Write-Ahead Logging (recommended)3PRAGMA journal_mode = DELETE; -- Default, safest4PRAGMA journal_mode = TRUNCATE; -- Faster than DELETE5PRAGMA journal_mode = MEMORY; -- In-memory (dangerous)6PRAGMA journal_mode = OFF; -- No journal (dangerous)7
8-- Synchronous mode9PRAGMA synchronous = FULL; -- Safest (default)10PRAGMA synchronous = NORMAL; -- Good for WAL mode11PRAGMA synchronous = OFF; -- Fastest (dangerous)12
13-- Cache size14PRAGMA cache_size = -64000; -- 64MB (negative = KB)15PRAGMA cache_size = 64000; -- 64000 pages16
17-- Memory-mapped I/O18PRAGMA mmap_size = 268435456; -- 256MB mmap19
20-- Temp store21PRAGMA temp_store = MEMORY; -- Store temp tables in memory22PRAGMA temp_store = FILE; -- Store temp tables on disk23
24-- Page size25PRAGMA page_size = 4096; -- Set page size (must be before creating tables)26
27-- Auto vacuum28PRAGMA auto_vacuum = INCREMENTAL; -- Incremental vacuum29PRAGMA auto_vacuum = FULL; -- Full vacuum on every commit30PRAGMA auto_vacuum = NONE; -- No auto-vacuum31
32-- Foreign keys33PRAGMA foreign_keys = ON; -- Enable foreign key checks34PRAGMA foreign_keys = OFF; -- Disable (for bulk imports)35
36-- Busy timeout37PRAGMA busy_timeout = 5000; -- Wait 5 seconds on lock38
39-- Integrity check40PRAGMA integrity_check; -- Check database integrity41PRAGMA quick_check; -- Quick integrity checkSchema PRAGMAs
sql
1-- Table info2PRAGMA table_info(users); -- Column definitions3PRAGMA table_xinfo(users); -- Extended column info4
5-- Foreign keys6PRAGMA foreign_key_list(users); -- Foreign key relationships7
8-- Indexes9PRAGMA index_list(users); -- Indexes on table10PRAGMA index_info('idx_users_email'); -- Index details11
12-- Database info13PRAGMA database_list; -- Attached databases14PRAGMA page_count; -- Total pages15PRAGMA page_size; -- Page size16PRAGMA freelist_count; -- Free pages17PRAGMA journal_mode; -- Current journal mode18PRAGMA encoding; -- Database encoding19PRAGMA auto_vacuum; -- Auto-vacuum modeImport & Export
Export Data
bash
1# Export to CSV2sqlite3 mydb.db ".mode csv" ".headers on" ".output users.csv" "SELECT * FROM users;" ".quit"3
4# Export to CSV (one-liner)5sqlite3 -header -csv mydb.db "SELECT * FROM users;" > users.csv6
7# Export to JSON8sqlite3 -json mydb.db "SELECT * FROM users;" > users.json9
10# Export to SQL11sqlite3 mydb.db ".dump" > backup.sql12
13# Export specific table14sqlite3 mydb.db ".dump users" > users.sql15
16# Export schema only17sqlite3 mydb.db ".schema" > schema.sqlImport Data
bash
1# Import CSV2sqlite3 mydb.db ".import --csv users.csv users" "SELECT COUNT(*) FROM users;"3
4# Import with headers (skip first row)5sqlite3 mydb.db ".import --skip 1 --csv users.csv users"6
7# Import from SQL8sqlite3 mydb.db < backup.sql9
10# Import from another SQLite database11sqlite3 mydb.db ".read other.db"12
13# Copy database14sqlite3 mydb.db ".dump" | sqlite3 newdb.dbUseful Patterns
Database Maintenance
sql
1-- VACUUM (reclaim space, defragment)2VACUUM;3
4-- Analyze (update statistics for query planner)5ANALYZE;6
7-- Integrity check8PRAGMA integrity_check;9
10-- Reindex all indexes11REINDEX;12
13-- Incremental vacuum (keep N pages of freelist)14PRAGMA incremental_vacuum(1000);Attach & Detach Databases
sql
1-- Attach another database2ATTACH DATABASE 'other.db' AS other;3
4-- Query attached database5SELECT * FROM other.users;6
7-- Detach8DETACH DATABASE other;Create Index
sql
1-- Simple index2CREATE INDEX idx_users_email ON users(email);3
4-- Unique index5CREATE UNIQUE INDEX idx_users_username ON users(username);6
7-- Composite index8CREATE INDEX idx_orders_user_status ON orders(user_id, status);9
10-- Partial index (SQLite 3.8+)11CREATE INDEX idx_active_users ON users(email) WHERE is_active = 1;12
13-- Covering index (SQLite 3.8+)14CREATE INDEX idx_cover ON users(email, username, age);15
16-- Drop index17DROP INDEX idx_users_email;18
19-- List indexes20.schema21PRAGMA index_list(users);Useful SQLite Functions
sql
1-- Date/time functions2SELECT datetime('now'); -- Current timestamp3SELECT date('now', '-1 day'); -- Yesterday4SELECT strftime('%Y-%m-%d', 'now'); -- Format date5SELECT julianday('now') - julianday('2024-01-01'); -- Days since date6
7-- String functions8SELECT upper('hello'); -- HELLO9SELECT lower('HELLO'); -- hello10SELECT length('hello'); -- 511SELECT substr('hello', 1, 3); -- hel12SELECT replace('hello', 'l', 'L'); -- heLLo13SELECT trim(' hello '); -- hello14SELECT group_concat(name, ', ') FROM users; -- Comma-separated list15
16-- Math functions17SELECT abs(-5); -- 518SELECT round(3.14159, 2); -- 3.1419SELECT min(1, 2, 3); -- 120SELECT max(1, 2, 3); -- 321
22-- Type functions23SELECT typeof(42); -- integer24SELECT typeof('hello'); -- text25SELECT typeof(3.14); -- real26
27-- JSON functions (SQLite 3.9+)28SELECT json_extract('{"name":"alice","age":30}', '$.name'); -- alice29SELECT json_array(1, 2, 3); -- [1,2,3]30SELECT json_object('name', 'alice', 'age', 30); -- {"name":"alice","age":30}31
32-- Random33SELECT abs(random()); -- Random integer34SELECT random() % 100; -- Random 0-99Troubleshooting
bash
1# Database is locked2PRAGMA busy_timeout = 5000; # Increase timeout3PRAGMA journal_mode = WAL; # Use WAL mode4
5# Corruption6PRAGMA integrity_check; # Check for corruption7sqlite3 mydb.db ".recover" > recovered.sql # Try to recover data8sqlite3 recovered.db < recovered.sql # Create new DB from recovered data9
10# Database file permissions11ls -la mydb.db # Check file permissions12chmod 644 mydb.db # Fix permissions13
14# WAL mode stuck15PRAGMA wal_checkpoint(PASSIVE); # Checkpoint WAL16PRAGMA wal_checkpoint(TRUNCATE); # Truncate WAL17
18# Check database size19SELECT page_count * page_size AS size FROM (SELECT pragma_page_count() AS page_count, pragma_page_size() AS page_size);20
21# Performance issues22PRAGMA compile_options; # Check compile options23PRAGMA optimize; # Run optimizerOutput Formatting
bash
1# In sqlite3 shell2.mode column # Column-aligned3.mode csv # CSV4.mode json # JSON (SQLite 3.33+)5.mode markdown # Markdown6.mode table # Box-drawing table7.mode insert # SQL INSERT statements8
9.headers on # Enable headers10.width 20 30 15 # Set column widths11
12# Command-line formatting13sqlite3 -header -csv mydb.db "SELECT * FROM users;" > users.csv14sqlite3 -json mydb.db "SELECT * FROM users;" | jq .15sqlite3 -column -header mydb.db "SELECT * FROM users;"